<template>
  <div class="todolist">
    <h3>todolist</h3>
    <Header :addTodo="addTodo" />
    <List :todos="todos" :deleteTodo="deleteTodo" :updateTodo="updateTodo" />
    <Footer
      :todos="todos"
      :checkAll="checkAll"
      :clearAllCheck="clearAllCheck"
    />
  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted, reactive, toRefs, watch } from 'vue'
import Header from './components/Header.vue'
import List from './components/List.vue'
import Footer from './components/Footer.vue'

import { Todo } from './types/todo'
import { saveTodos, readTodos } from './utils/localStorageUtils'
export default defineComponent({
  name: 'TodoList',
  components: {
    Header,
    List,
    Footer
  },
  setup () {
    // 定义一个数组数据
    const state = reactive<{ todos: Todo[] }>({
      todos: []
    })

    // 界面加载完毕后过了一会再读取数据
    onMounted(() => {
      setTimeout(() => {
        state.todos = readTodos()
      }, 1000)
    })
    const addTodo = (todo: Todo) => {
      state.todos.unshift(todo)
    }

    const deleteTodo = (index: number) => {
      state.todos.splice(index, 1)
    }
    // 修改todo的isCheck属性的状态
    // 夫级组件的数据不要让子级组件修改，定义方法让子集调用
    const updateTodo = (toto: Todo, isCheck: boolean) => {
      toto.isCheck = isCheck
      console.log(toto)
    }

    // 全选 或者是全不选
    const checkAll = (isCheck: boolean) => {
      state.todos.forEach((todo) => {
        todo.isCheck = isCheck
      })
    }

    // 清除所有选中的数据
    const clearAllCheck = () => {
      state.todos = state.todos.filter((todo) => !todo.isCheck)
    }
    // 监视操作：如果todos数组的数据变化了，直接存储到浏览器中的缓存中
    // watch(() => state.todos, (value) => {
    //   // 保存到浏览器的缓存中
    //   // localStorage.setItem('todos_key', JSON.stringify(value))
    //   saveTodos(value)
    // }, {
    //   deep: true
    // })
    // 改写
    watch(() => state.todos, saveTodos, { deep: true })

    return {
      ...toRefs(state),
      addTodo,
      deleteTodo,
      updateTodo,
      checkAll,
      clearAllCheck
    }
  }
})
</script>

<style scoped>
.todolist {
  margin: 0 auto 20px;
  margin-top: 10px;
  width: 500px;
  border: 1px solid #ccc;
  padding: 0 10px;
}
h3 {
  text-align: center;
}
</style>
